<template>
  <el-dialog
      v-model="visible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
      @closed="handleClosed"
  >
    <el-form
        :model="formData"
        label-width="120px"
        ref="formRef"
        :rules="rules"
    >
      <el-form-item label="Name" prop="name">
        <el-input v-model="formData.name" placeholder="Please enter name" />
      </el-form-item>
      <el-form-item label="Status" prop="status">
        <el-select v-model="formData.status" placeholder="Please select status">
          <el-option label="Active" value="1" />
          <el-option label="Inactive" value="0" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">Cancel</el-button>
      <el-button type="primary" @click="submitForm">Submit</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

interface TableItem {
  id?: number
  name: string
  status: string
}

interface Props {
  modelValue: boolean
  rowData?: TableItem | null
}

const props = defineProps<Props>()
const emit = defineEmits(['update:modelValue', 'submit'])

const formRef = ref<FormInstance>()
const formData = ref<TableItem>({
  name: '',
  status: '1'
})

// Validation rules
const rules = ref<FormRules>({
  name: [
    { required: true, message: 'Please input name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Length should be 2 to 50', trigger: 'blur' }
  ],
  status: [
    { required: true, message: 'Please select status', trigger: 'change' }
  ]
})

// Dialog visibility control
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// Dialog title based on operation
const dialogTitle = computed(() => {
  return props.rowData?.id ? 'Edit Item' : 'Create Item'
})

// Initialize form with row data
watch(() => props.rowData, (newVal) => {
  if (newVal) {
    formData.value = { ...newVal }
  } else {
    formData.value = {
      name: '',
      status: '1'
    }
  }
}, { immediate: true })

// Handle form submission
const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    emit('submit', formData.value)
    visible.value = false
  } catch (error) {
    console.log('Form validation failed')
  }
}

// Reset form when dialog closes
const handleClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
</style>